package com.base.lock.zk;

import java.util.concurrent.TimeUnit;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.base.lock.zk.example.ZkLock;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/zk")
public class ZkController {

	@Autowired
	private CuratorFramework curatorFramework;
	
	
	@GetMapping("/lock")
	public String lock() {
		log.info("我进入了方法!");
		try (ZkLock lock = new ZkLock()) {
			if (lock.getLock("order")) {
				log.info("我获取到了锁！");
				Thread.sleep(5000);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.info("方法执行完成");
		return "方法执行完成";
	}
	
	@GetMapping("/lock/curator")
	public String lockCurator() {
		log.info("我进入了方法!");
		InterProcessMutex lock = new InterProcessMutex(curatorFramework, "/order");
		try {
			if (lock.acquire(1,TimeUnit.SECONDS)) {
				log.info("我获取到了锁！");
				Thread.sleep(5000);
			}else {
				log.info("我等待了1秒,没有获取到锁！");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				lock.release();
				log.info("释放锁");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		log.info("方法执行完成");
		return "方法执行完成";
	}
}
